﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace NETCORE.JWT.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OAuthController : ControllerBase
    {
        private TokenParameter Config_TokenParameter;

        public OAuthController(IOptions<TokenParameter> option)
        {
            Config_TokenParameter = option.Value;
        }


        [HttpGet]
        [Route("token")]
        public ActionResult GetAccessToken(string username, string password)
        {
            if (username != "admin" || password != "admin")
            {
                return BadRequest("Invalid Request");
            }

            var claims = new[]
            {
                new Claim (ClaimTypes.Name,username),
                new Claim(ClaimTypes.Role,"")
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Config_TokenParameter.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(Config_TokenParameter.Issuer, Config_TokenParameter.Audience, claims, expires: DateTime.UtcNow.AddMinutes(Config_TokenParameter.AccessExpiration), signingCredentials: credentials);
            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return Ok(token);
        }
    }
}
